package com.lottery.ruok.lottrey.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.applozic.mobicomkit.api.account.register.RegistrationResponse;
import com.applozic.mobicomkit.api.account.user.MobiComUserPreference;
import com.applozic.mobicomkit.api.account.user.PushNotificationTask;
import com.applozic.mobicomkit.api.account.user.User;
import com.applozic.mobicomkit.api.account.user.UserLoginTask;
import com.applozic.mobicomkit.api.account.user.UserLogoutTask;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.ConversationActivity;
import com.applozic.mobicomkit.uiwidgets.notification.MTNotificationBroadcastReceiver;
import com.google.gson.Gson;
import com.ks.gopush.cli.GoPushCli;
import com.ks.gopush.cli.PushMessage;
import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.MyApplication;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.ReceiverPushInfoManager;
import com.lottery.ruok.lottrey.adapter.CommonFragmentPagerAdapter;
import com.lottery.ruok.lottrey.chat.RongCloudChatActivityHelper;
import com.lottery.ruok.lottrey.chat.RongCloudChatManager;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.dialog.ProclamationDialog;
import com.lottery.ruok.lottrey.eventbusObject.GoHomeEvent;
import com.lottery.ruok.lottrey.eventbusObject.GotoBuyPage;
import com.lottery.ruok.lottrey.eventbusObject.LogOut;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.eventbusObject.RefrashManagerEvent;
import com.lottery.ruok.lottrey.eventbusObject.RefrashRoomEvent;
import com.lottery.ruok.lottrey.eventbusObject.RefreshRoomStatus;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.eventbusObject.UpdateApk;
import com.lottery.ruok.lottrey.fragment.BaseFragment;
import com.lottery.ruok.lottrey.fragment.BuyLotteryMainFragment;
import com.lottery.ruok.lottrey.fragment.ChatMainFragment;
import com.lottery.ruok.lottrey.fragment.HomeMainFragment;
import com.lottery.ruok.lottrey.fragment.MemberMainFragment;
import com.lottery.ruok.lottrey.fragment.PrizeMainFragment;
import com.lottery.ruok.lottrey.retrofitModule.BaseModel;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetActivitiesAwardRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetActivitiesKeysRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetChatRoomCurrentStatus;
import com.lottery.ruok.lottrey.retrofitModule.request.GetHasSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetMsgRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetPushInfoRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomAdminResquest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.LogOutRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.ChatRoomStatus;
import com.lottery.ruok.lottrey.retrofitModule.response.GetActivitiesAwardResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetActivitiesKeysResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetHasSMSResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetMsgResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetPushTokenResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomAdminResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OperationSuccessResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.StringUtils;
import com.lzy.widget.AlphaIndicator;
import com.lzy.widget.AlphaView;
import com.tencent.tinker.loader.shareutil.ShareConstants;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import ui.NoScrollViewPager;
import utils.Base64Utils;
import utils.LogUtil;
import utils.RSAUtils;
import utils.SSLSocketClient;
import utils.Utils;

public class MainActivity extends BaseActivity {
    private static final long INTERVAL_TIME = 90;
    private static final long DELAY_TIME = 90;
    @BindView(R.id.chat_layout)
    View chatLayout;
    @BindView(R.id.view_bottom_menu_chat)
    AlphaView viewBottomMenuChat;
    //上次按下返回键的系统时间
    private long lastBackTime = 0;
    private long lastGetPushTime = 0;
    public NoScrollViewPager viewPager;
    /**
     * ThreadLocal是一个关于创建线程局部变量的类。
     * 通常情况下，我们创建的变量是可以被任何一个线程访问并修改的。而使用ThreadLocal创建的变量只能被当前线程访问，其他线程则无法访问和修改。
     * 在Android中，Looper类就是利用了ThreadLocal的特性，保证每个线程只存在一个Looper对象。
     */
    private ThreadLocal<GoPushCli> local = new ThreadLocal<>();
    private int mOnlineIndex = 1;
    //    private GoPushCli cli;
    OkHttpClient client;
    private ProclamationDialog proclamationDialog;
    private MTNotificationBroadcastReceiver notificationBroadcastReceiver;
    private List<BaseFragment> fragments = new ArrayList<>();
    private Intent intent;
    private Disposable subscribe;
    private GetActivitiesKeysResponse mActivitiesKeysResponse;
    private volatile boolean lock = true;
    private long mStartActivitiesPollTime;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.getBooleanExtra("from_pay", false)) {
            viewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    viewPager.setCurrentItem(4);
                }
            }, 100);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(GotoBuyPage favorDeleted) {
        viewPager.setCurrentItem(1);
    }

    private void addNotification(int id, PushMessage message) {


        String channelId = null;
        String channelName;
        int importance;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            channelId = "subscribe";
            channelName = "系统消息";
            importance = NotificationManager.IMPORTANCE_DEFAULT;
            createNotificationChannel(this, channelId, channelName, importance);
        }
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher);
        //获取通知服务的对象
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        //===============通知窗口的属性设置===============
        builder.setAutoCancel(true);//点击后自动消失
        builder.setChannelId(channelId);//8.0消息通道
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(bitmap);
        builder.setTicker(BuildConfig.app_name);//在状态栏跳出时显示的内容
        builder.setContentTitle(BuildConfig.app_name);//在下拉条里显示的通知的标题
        builder.setContentText(message.getMsg().getAps().getAlert());//标题下的内容摘要
        builder.setDefaults(Notification.DEFAULT_ALL);//设置通知接收时，系统对应的提醒方式，震动，声音等

        //创建意图,从哪个Activity跳转到哪个Activity的意图
        Intent mIntent = new Intent(this, MainActivity.class);
        if (message.getMsg().getAps().getType() != null && message.getMsg().getAps().getType().equals("charge_success")) {
            mIntent.putExtra("from_pay", true);
        }
        //获得一个用于跳转Activity的延迟意图（何时触发该意图不确定，而Intent是即时的）
        //一般跳转Activity的时候，我们需要把最后一个参数改为PendingIntent.FLAG_UPDATE_CURRENT,这样在启动的Activity里就可以用接收Intent传送数据的方法正常接收。
        PendingIntent activity = PendingIntent.getActivity(this, 1, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //把这个延迟意图塞到通知里
        builder.setContentIntent(activity);
        //设置当点击通知后，通知是否自动消失
        builder.setAutoCancel(true);

        //把所有设置联合起来，返回一个新的notification
        Notification build = new NotificationCompat.BigTextStyle(builder).bigText(message.getMsg().getAps().getAlert()).build();
        notificationManager.notify(id, build);
    }

    protected void getService() {
        if (Common.service_url == null) {
            try {
                RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("contact_support_link")
                        .compose(RxHelper.<GetHasSMSResponse>handleResultReConnection())
                        .subscribe(new RxSubscribe<GetHasSMSResponse>(this) {
                            @Override
                            protected void _onNext(GetHasSMSResponse getHasSMSResponse) {
                                if (getHasSMSResponse != null && getHasSMSResponse.getValue() != null && !getHasSMSResponse.getValue().toString().equals("null")) {
                                    //                            Utils.openBrowser(getHasSMSResponse.getValue().toString(), getActivity());

                                    Common.service_url = getHasSMSResponse.getValue().toString().replaceAll("\"", "");
                                } else {
                                    //  Utils.showToast(Common.NO_SERVICE);
                                }
                            }

                            @Override
                            protected boolean showDialog() {
                                return false;
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent1(StartConnect event) {
//        setPushClient();
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(UpdateApk event) {
        if (proclamationDialog != null && proclamationDialog.isShowing()) {
            proclamationDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent3(RefrashManagerEvent event) {
        //更新房间管理者
        getRoomAdmins();
    }

    private void setPrizePushClient() {
        try {
            //请求一个url去获取开奖推送的token
            final OkHttpClient httpClient;
            final String push_url;
            if (BuildConfig.COMPANY_CODE.equals("speedup")) {
                httpClient = new OkHttpClient.Builder()
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                        .build();
                push_url = "webtcp.ruok.co";
            } else if (BuildConfig.COMPANY_CODE.equals("yunding")) {
                httpClient = new OkHttpClient.Builder()
                        .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                        .build();
                push_url = "test111.ruok.co";
            } else {
                httpClient = new OkHttpClient.Builder()
                        .build();
                push_url = "www.websocket.co";
            }
            Request httpRequest = new Request.Builder()
                    .url("https://" + push_url + "/platform/web/v1/draw/token")
                    .build();
            Call httpCall = httpClient.newCall(httpRequest);
            httpCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    httpClient.dispatcher().cancelAll();

                    tryPirzePushLater(false);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response != null && response.body() != null) {
                        String json = response.body().string();
                        if (json != null) {
                            Gson gson = new Gson();
                            GetPushTokenResponse getPushTokenResponse = gson.fromJson(json, GetPushTokenResponse.class);
                            if (getPushTokenResponse != null) {
                                if (getPushTokenResponse.getCode() == 200) {
                                    try {
                                        InputStream inPrivate = new ByteArrayInputStream(Common.rsa_private_key.getBytes("UTF-8"));
                                        PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
                                        String token = new String(RSAUtils.decryptData(Base64Utils.decode(getPushTokenResponse.getData().getToken()), privateKey));
                                        String wsUrl = String.format("wss://" + push_url + "/platform/web/v1/ws/v2/link?key=%s&code=%s&token=%s&devType=%s", Utils.isEmpty(UserInfo.getUsername()) ? System.currentTimeMillis() + "" : UserInfo.getUsername(), BuildConfig.prize_push_name, token, "android");
                                        if (BuildConfig.COMPANY_CODE.equals("huobaocaipiao")) {//测试环境
                                            client = new OkHttpClient.Builder()
                                                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                                                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                                                    .pingInterval(60, TimeUnit.SECONDS)
                                                    .build();
                                        } else if (BuildConfig.COMPANY_CODE.equals("yunding")) {//预发布环境
                                            client = new OkHttpClient.Builder()
                                                    .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
                                                    .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                                                    .pingInterval(60, TimeUnit.SECONDS)
                                                    .build();
                                        } else {
                                            client = new OkHttpClient.Builder()
                                                    .pingInterval(60, TimeUnit.SECONDS)
                                                    .build();
                                        }
                                        Request request = new Request.Builder().url(wsUrl).build();
                                        client.newWebSocket(request, new WebSocketListener() {
                                            @Override
                                            public void onOpen(WebSocket webSocket, Response response) {
                                                //一旦连接上了拉一下消息
                                                EventBus.getDefault().post(new StartPrzePush());

                                                getService();
                                            }

                                            @Override
                                            public void onMessage(WebSocket webSocket, String text) {
                                                //处理推送信息管理者
                                                ReceiverPushInfoManager.receive(MainActivity.this, text);

                                            }

                                            @Override
                                            public void onClosing(WebSocket webSocket, int code, String reason) {
                                            }

                                            @Override
                                            public void onClosed(WebSocket webSocket, int code, String reason) {
                                            }

                                            @Override
                                            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                                                if (webSocket != null) {
                                                    webSocket.cancel();
                                                }
                                                client.dispatcher().cancelAll();

                                                //隔一段时间以后重连
                                                tryPirzePushLater(false);
                                            }
                                        });
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    tryPirzePushLater(false);
                                }
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void tryPirzePushLater(final boolean onStart) {
        if (client != null) {
            client.dispatcher().cancelAll();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!onStart) {
                        TimeUnit.SECONDS.sleep(10);
                    }
                    setPrizePushClient();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

//    private void setPushClient() {
//        if (cli != null) {
//            cli.destory(true);
//            cli = null;
//        }
//        local.set(new GoPushCli("35.229.162.61", 8090, MyApplication.UUID + BuildConfig.APPLICATION_ID, 5,
//                new Listener() {
//                    @Override
//                    public void onOpen() {
//                    }
//
//                    @Override
//                    public void onOnlineMessage(PushMessage message) {
//                        if (message.getMsg().getAps().getType() != null) {
//                            if (message.getMsg().getAps().getType().equals("charge_success")) {
//                                EventBus.getDefault().post(new ChargePush());
//                            } else if (message.getMsg().getAps().getType().equals("chatGroup_changed")) {
//                                Utils.showToast("当前已经切换新的聊天室，关闭应用，重新打开");
//                            }
//                        }
//                        if (!ApplozicClient.getInstance(getApplicationContext()).isNotificationDisabled()) {
//                            addNotification(mOnlineIndex++, message);
//                        }
//                    }
//
//                    @Override
//                    public void onOfflineMessage(List<PushMessage> messages) {
//                        if (messages != null) {
//                            if (!ApplozicClient.getInstance(getApplicationContext()).isNotificationDisabled()) {
//                                int i = 0;
//                                for (PushMessage message : messages) {
//                                    if (message.getMsg().getAps().getType() != null && message.getMsg().getAps().getType().equals("charge_success")) {
//                                        EventBus.getDefault().post(new ChargePush());
//                                    }
//                                    i++;
//                                    addNotification(i, message);
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e, String message) {
//
//                    }
//
//                    @Override
//                    public void onClose() {
//
//                    }
//                }));
//        cli = local.get();
//        new Thread() {
//            public void run() {
//                if (cli != null) {
//                    cli.start(true, 0, 0);
//                }
//            }
//        }.start();
//    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册聊天室接收器
        registerChatReceiver();
        getService();
//        setPushClient();
        tryPirzePushLater(true);

        setContentView(R.layout.activity_main);
        if (UserInfo.getStartActivitiesPollTime() == 0) {
            UserInfo.setStartActivitiesPollTime(System.currentTimeMillis());
        }
        mStartActivitiesPollTime = UserInfo.getStartActivitiesPollTime();
        ButterKnife.bind(this);
        showNotice();
        EventBus.getDefault().register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        viewPager = findViewById(R.id.viewPager);
        fragments.add(new HomeMainFragment());
        fragments.add(new BuyLotteryMainFragment());
        fragments.add(new PrizeMainFragment());
        fragments.add(new ChatMainFragment());
        fragments.add(new MemberMainFragment());
        viewPager.setAdapter(new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                getRoomStatus();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (position == 0) {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        getWindow().getDecorView().setSystemUiVisibility(
                                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        AlphaIndicator alphaIndicator = findViewById(R.id.alphaIndicator);
        alphaIndicator.setViewPager(viewPager);

        MyApplication.isStart = false;

        getRoom();

        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE)
                .request();

        checkUpdate(true, false);
        initDialog();
        getRoomStatus();
        RongCloudChatManager.connect();
        //融云连接状态的监听
        RongIM.setConnectionStatusListener(new MyConnectionStatusListener());
        getActivitiesKeys();
    }

    /**
     * 活动开关
     */
    private void getActivitiesKeys() {
        RetrofitBase.getRetrofit().create(GetActivitiesKeysRequest.class)
                .getResult()
                .compose(RxHelper.<GetActivitiesKeysResponse>handleResult())
                .subscribe(new RxSubscribe<GetActivitiesKeysResponse>(this) {
                    @Override
                    protected void _onNext(GetActivitiesKeysResponse getActivitiesKeysResponse) {
                        EventBus.getDefault().post(getActivitiesKeysResponse);
                        //当前活动开关未关闭,并且是登陆状态
                        mActivitiesKeysResponse = getActivitiesKeysResponse;
                        startPoll();
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    /**
     * 判断是否开启轮询
     */
    private void startPoll() {
        if (mActivitiesKeysResponse.getEnable_activities_icon() == 1
                || mActivitiesKeysResponse.getEnable_activities() == 1
                || mActivitiesKeysResponse.getEnable_activities_panel() == 1) {
            if (UserInfo.getIsTest() != 0 || UserInfo.getIsTry() != 0) {
                return;
            } else{
                if (!Utils.isEmpty(UserInfo.getToken())) pollActivities();
            }

        }
    }


    private void registerChatReceiver() {
        //过滤器
        IntentFilter intentFilter = new IntentFilter(BuildConfig.APPLICATION_ID + ".send.notification");
        notificationBroadcastReceiver = new MTNotificationBroadcastReceiver();
        registerReceiver(notificationBroadcastReceiver, intentFilter);
    }

    private void initDialog() {
        proclamationDialog = new ProclamationDialog(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        //ContactUtils.uploadContacts(this);
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {

    }


    private void getRoom() {
        getPushInfo();

        Observable<BaseModel<GetRoomResponse>> observable;
        if (TextUtils.isEmpty(UserInfo.getToken())) {
            observable = RetrofitBase.getRetrofit().create(GetRoomRequest.class)
                    .getResultByUuid(MyApplication.UUID);
        } else {
            observable = RetrofitBase.getRetrofit().create(GetRoomRequest.class)
                    .getResult(UserInfo.getToken(), UserInfo.getUsername());
        }

        try {
            observable.compose(RxHelper.<GetRoomResponse>handleResultReConnection())
                    .subscribe(new RxSubscribe<GetRoomResponse>(MainActivity.this) {
                        @Override
                        protected void _onNext(final GetRoomResponse getRoomResponse) {
                            if (getRoomResponse != null && getRoomResponse.getData() != null) {
                                UserInfo.setRoomNumCount(getRoomResponse.getData().getUser_count());
                                UserInfo.setRoomId(getRoomResponse.getData().getRoom_id());
//                                UserInfo.setChatRoomInfo(getRoomResponse.getData());
//                                ApplozicClient.getInstance(getApplicationContext()).setRoomId(getRoomResponse.getData().getThird_room_id());
                                UserInfo.setAdmin(getRoomResponse.getData().getAdmin());
                                UserInfo.setChatroom_role(getRoomResponse.getData().getChatroom_role());
                                // UserInfo.setLocalRoomId(getRoomResponse.getData().getRoom_id());
                                UserInfo.setRoomName(getRoomResponse.getData().getRoom_name());
                                Common.fobid_words = getRoomResponse.getData().getFobid_words();
                                getRoomAdmins();

                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }


        UserLoginTask.TaskListener listener = new UserLoginTask.TaskListener() {
            @Override
            public void onSuccess(RegistrationResponse registrationResponse, Context context) {
                if (MobiComUserPreference.getInstance(context).isRegistered()) {
                    PushNotificationTask pushNotificationTask;
                    PushNotificationTask.TaskListener listener = new PushNotificationTask.TaskListener() {
                        @Override
                        public void onSuccess(RegistrationResponse registrationResponse) {

                        }

                        @Override
                        public void onFailure(RegistrationResponse registrationResponse, Exception exception) {

                        }
                    };

                    pushNotificationTask = new PushNotificationTask(MyApplication.UUID, listener, MainActivity.this);
                    pushNotificationTask.execute((Void) null);
                }
            }

            @Override
            public void onFailure(RegistrationResponse registrationResponse, Exception exception) {

            }
        };
        User user = new User();
        user.setAuthenticationTypeId(User.AuthenticationType.CLIENT.getValue());
        if (!UserInfo.getToken().equals("")) {
            user.setUserId(UserInfo.getUsername()); //userId it can be any unique user identifier
            user.setPassword(Utils.md5(UserInfo.getUsername()));
        } else {
            user.setUserId(Common.CHAT_ACCOUNT); //userId it can be any unique user identifier
            user.setPassword(Utils.md5(Common.CHAT_PASSWORD));
        }
        new UserLoginTask(user, listener, MainActivity.this).execute((Void) null);
    }

    /**
     * 获取房间管理者
     */
    public void getRoomAdmins() {
        if (StringUtils.isNotEmpty(UserInfo.getRoomId())) {
            try {
                RetrofitBase.getRetrofit().create(GetRoomAdminResquest.class)
                        .getResult(UserInfo.getToken(), UserInfo.getRoomId())
                        .compose(RxHelper.<GetRoomAdminResponse>handleResultReConnection())
                        .subscribe(new RxSubscribe<GetRoomAdminResponse>(this) {
                            @Override
                            protected void _onNext(final GetRoomAdminResponse getRoomAdminResponses) {
                                UserInfo.setRoomAdminInfo(getRoomAdminResponses.getList());
                            }

                            @Override
                            protected boolean showDialog() {
                                return false;
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //捕获返回键按下的事件
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //获取当前系统时间的毫秒数
            long currentBackTime = System.currentTimeMillis();
            //比较上次按下返回键和当前按下返回键的时间差，如果大于2秒，则提示再按一次退出
            if (currentBackTime - lastBackTime > 2 * 1000) {
                Toast.makeText(MainActivity.this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
                lastBackTime = currentBackTime;
            } else { //如果两次按下的时间差小于2秒，则退出程序
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LogOut event) {
        if (subscribe != null && !subscribe.isDisposed()) {//退出登陆结束轮询
            subscribe.dispose();
        }

        viewPager.setCurrentItem(0);
        if (client != null) {
            client.dispatcher().cancelAll();
        }
        getRoom();
        RongCloudChatManager.reconnect();
        intent = null;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(GoHomeEvent event) {
        viewPager.setCurrentItem(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LoginSuccess event) {
        getRoom();
        showNotice();
        if (mActivitiesKeysResponse != null) {
            //开启轮询
            startPoll();
        }
//        tryPirzePushLater(true);
//        updateAccount(new AfterUpdateAccount() {
//            @Override
//            public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
//                int chatroom_block = getProfileResponse.getUser().getChatroom_block();
//                if (chatroom_block != 0) {
//                    UserInfo.setChatroom_block(chatroom_block);
//                }
//            }
//        });
        RongCloudChatManager.reconnect();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent3(RefrashRoomEvent event) {
        getRoom();
    }

    @Override
    protected void onDestroy() {
//        unregisterReceiver(notificationBroadcastReceiver);
        EventBus.getDefault().unregister(MainActivity.this);
        if (subscribe != null && !subscribe.isDisposed()) {
            subscribe.dispose();
        }
        super.onDestroy();
    }

    @OnClick(R.id.chat_layout)
    public void onViewClicked() {
//        if (UserInfo.getChatroom_block() == 2) {
//            Utils.showToast("你已经被从聊天室移除");
//            return;
//        }
//        gotoChatRoom();
       /* if (UserInfo.getToken().equals("")) {
            utils.Utils.showToast("请您先登录");
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
            return;
        }*/
        if (StringUtils.isNotEmpty(UserInfo.getRoomId())) {
            if (UserInfo.getChatroom_block()!=2) {
                String defaultLottery = UserInfo.getDefaultLottery();
                if (StringUtils.isNotEmpty(defaultLottery)) {
                    RongCloudChatActivityHelper.startChatRoomChat(MainActivity.this, UserInfo.getRoomId(), true, defaultLottery, UserInfo.getRoomName());
                } else {
                    RongCloudChatActivityHelper.startChatRoomChat(MainActivity.this, UserInfo.getRoomId(), true, "bjpk10", UserInfo.getRoomName());
                }
            }else {
                Toast.makeText(MainActivity.this, "您已经被移出群聊", Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(MainActivity.this, "聊天室不存在，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    private void getPushInfo() {
        DisposableObserver disposableObserver = RetrofitBase.getRetrofit().create(GetPushInfoRequest.class)
                .getResult(UserInfo.getToken().equals("") ? null : UserInfo.getToken(), MyApplication.UUID + BuildConfig.APPLICATION_ID)
                .compose(RxHelper.<OperationSuccessResponse>handleResultReConnection())
                .subscribeWith(new RxSubscribe<OperationSuccessResponse>(MainActivity.this) {
                    @Override
                    protected void _onNext(OperationSuccessResponse operationSuccessResponse) {

                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
        disposables.add(disposableObserver);
    }

    /**
     * 获取运营商聊天室开关状态
     */
    public void getRoomStatus() {
        RetrofitBase.getRetrofit().create(GetChatRoomCurrentStatus.class).getResult()
                .compose(RxHelper.<ChatRoomStatus>handleResultReConnection())
                .subscribe(new RxSubscribe<ChatRoomStatus>(this) {
                    @Override
                    protected void _onNext(ChatRoomStatus chatRoomStatus) {
                        if (chatRoomStatus != null) {
                            ChatRoomStatus.DataBean data = chatRoomStatus.getData();
                            if (data != null) {
                                switch (data.getStatus()) {
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_OPEN:
                                        UserInfo.setChatStatus(data.getStatus());
                                        viewBottomMenuChat.setVisibility(View.VISIBLE);
                                        chatLayout.setVisibility(View.VISIBLE);
                                        break;
                                    case ChatRoomStatus.CHAT_ROOM_STATUS_CLOSE:
                                        UserInfo.setChatStatus(data.getStatus());
                                        viewBottomMenuChat.setVisibility(View.GONE);
                                        chatLayout.setVisibility(View.GONE);
                                        break;
                                }
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getRoomStatus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshRoomStatus(RefreshRoomStatus refreshRoomStatus) {
        getRoomStatus();
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(Context context, String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.setShowBadge(true);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(
                NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
    }

    private class MyConnectionStatusListener implements RongIMClient.ConnectionStatusListener {

        @Override
        public void onChanged(RongIMClient.ConnectionStatusListener.ConnectionStatus connectionStatus) {

            switch (connectionStatus) {

                case CONNECTED://连接成功。

                    break;
                case DISCONNECTED://断开连接。

                    break;
                case CONNECTING://连接中。

                    break;
                case NETWORK_UNAVAILABLE://网络不可用。

                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线
                    /*runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "该账户已在其他设备登陆", Toast.LENGTH_SHORT).show();
                            loginout();
                        }
                    });*/

                    break;
            }
        }
    }

    //退出登陆
    private void loginout() {
        RetrofitBase.getRetrofit().create(LogOutRequest.class)
                .getResult(UserInfo.getToken())
                .compose(RxHelper.<OperationSuccessResponse>handleResult())
                .subscribe(new RxSubscribe<OperationSuccessResponse>(MainActivity.this) {
                    @Override
                    protected void _onNext(OperationSuccessResponse operationSuccessResponse) {
                        UserLogoutTask.TaskListener userLogoutTaskListener = new UserLogoutTask.TaskListener() {
                            @Override
                            public void onSuccess(Context context) {

                            }

                            @Override
                            public void onFailure(Exception exception) {

                            }
                        };
                        UserLogoutTask userLogoutTask = new UserLogoutTask(userLogoutTaskListener, MainActivity.this);
                        userLogoutTask.execute((Void) null);

                        logOut();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        UserLogoutTask.TaskListener userLogoutTaskListener = new UserLogoutTask.TaskListener() {
                            @Override
                            public void onSuccess(Context context) {

                            }

                            @Override
                            public void onFailure(Exception exception) {

                            }
                        };
                        UserLogoutTask userLogoutTask = new UserLogoutTask(userLogoutTaskListener, MainActivity.this);
                        userLogoutTask.execute((Void) null);

                        logOut();

                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void showNotice() {
        if (StringUtils.isNotEmpty(UserInfo.getToken())) {
            if (UserInfo.getIsTest() != 1 || UserInfo.getIsTry() == 1) {
                RetrofitBase.getRetrofit().create(GetMsgRequest.class).getResult(UserInfo.getToken())
                        .compose(RxHelper.<ArrayList<GetMsgResponse>>handleResult())
                        .subscribe(new RxSubscribe<ArrayList<GetMsgResponse>>(this) {
                            @Override
                            protected void _onNext(ArrayList<GetMsgResponse> getMsgResponses) {
                                if (getMsgResponses.size() > 0) {
                                    for (GetMsgResponse smg : getMsgResponses) {
                                        if (smg.getIs_alert().equals("1")) {

                                            if (intent == null) {
                                                intent = new Intent(MainActivity.this, NoticeDialogActivity.class);
                                                intent.putExtra("notice_responses", getMsgResponses);
                                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                startActivity(intent);
                                            }

                                        }
                                    }
                                }
                            }

                            @Override
                            protected boolean showDialog() {
                                return false;
                            }
                        });
            }
        }

    }

    /**
     * 轮询活动可领取奖励
     */
    private void pollActivities() {
        subscribe = Observable.interval(DELAY_TIME, INTERVAL_TIME, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        LogUtil.d(String.format("get_activities_poll:%s", aLong));
                        getActivities();
                    }
                });
    }

    /**
     * 获取是否有可领取的活动奖励
     */
    private void getActivities() {
        LogUtil.d(String.format("当前LOCK---%s", lock));
        if (lock) {
            RetrofitBase.getRetrofit().create(GetActivitiesAwardRequest.class)
                    .getResult(UserInfo.getToken(), mStartActivitiesPollTime)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new RxSubscribe<GetActivitiesAwardResponse>(this) {
                        @Override
                        protected void _onNext(GetActivitiesAwardResponse response) {
                            lock = true;
                            LogUtil.d(String.format("当前是否有任务---%s", response.getData()));
                            if (1 == response.getData()) {
                                UserInfo.setStartActivitiesPollTime(System.currentTimeMillis());
                                mStartActivitiesPollTime = UserInfo.getStartActivitiesPollTime();
                                if (!getTopActivity(MainActivity.this).equals(GetAwardActivityDialog.class.getName())) {
                                    startActivity(new Intent(MainActivity.this, GetAwardActivityDialog.class));
                                }
                            }
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }

                        @Override
                        protected void onStart() {
                            super.onStart();
                            lock = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            lock = true;
                        }
                    });
        }
        LogUtil.d(String.format("当前--LOCK--onNet--%s", lock));
    }

    //判断当前界面显示的是哪个Activity
    public static String getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        return cn.getClassName();
    }
}